const { Op } = require('sequelize');
const models = require('../models');
const { v4: uuidv4 } = require('uuid');
const DateUtils = require('../utils/dateUtils');
const { sys_role_model: SysRoleModel, sys_role_menu_model: SysRoleMenuModel,sys_menu_model: SysMenuModel } = models;
const { realDelete } = require('../config/system');
class RoleService {
  // 获取角色列表
  async getRoleList({ page, size, keywords, status }) {
    const where = {
        isDeleted: 0 // 未删除
    };
    if (keywords) {
      where.name = { [Op.like]: `%${keywords}%` };
    }
    if (status !== undefined) {
      where.status = status;
    }

    return await SysRoleModel.findAndCountAll({
      where,
      offset: (page - 1) * size,
      limit: size,
      order: [['sort']]
    });
  }

  // 获取角色详情
  async getRoleById(id) {
    const role = await SysRoleModel.findOne({
      where: { id, is_deleted: 0 }
    });
    if (!role) {
      throw new Error('角色不存在');
    }
    return role;
  }

  // 创建角色
  async createRole(roleData) {
    if(roleData.code){
      // 检查角色编码是否已存在
      const existRole = await SysRoleModel.findOne({
        where: { code: roleData.code, isDeleted: 0 }
      });
      if (existRole) {
        throw new Error('角色编码已存在');
      }
    }
    const result = await SysRoleModel.create({
      ...roleData,
      code: roleData.code || `ROLE_${uuidv4().replace(/-/g, '').substring(0, 8).toUpperCase()}`,
      createTime: DateUtils.getCurrentTime(),
      isDeleted: 0
    });

    return result;
  }

  // 更新角色
  async updateRole(id, roleData) {
    const role = await SysRoleModel.findOne({
      where: { id, is_deleted: 0 }
    });
    if (!role) {
      throw new Error('角色不存在');
    }

    // 如果修改角色编码，需要检查是否重复
    if (roleData.code && roleData.code !== role.code) {
      const existRole = await SysRoleModel.findOne({
        where: { code: roleData.code, is_deleted: 0, id: { [Op.ne]: id } }
      });
      if (existRole) {
        throw new Error('角色编码已存在');
      }
    }

    await role.update({
      ...roleData,
      update_time: new Date(),
      update_by: roleData.update_by
    });

    return role;
  }

  // 删除角色
  async deleteRoles(ids) {
    // 使用事务确保数据一致性
    const t = await models.sequelize.transaction();
    try {
      for (const id of ids) {
        const role = await SysRoleModel.findOne({
          where: { id, is_deleted: 0 },
          transaction: t
        });
        if (!role) {
          throw new Error(`角色ID ${id} 不存在`);
        }

        if (realDelete) {
          // 真实删除
          await role.destroy({ transaction: t });
        } else {
          // 软删除
          await role.update({
            is_deleted: 1,
            update_time: new Date()
          }, { transaction: t });
        }
      }
      await t.commit();
    } catch (error) {
      await t.rollback();
      throw error;
    }
  }

  // 分配角色菜单
  async assignRoleMenus(roleId, menuIds) {
    const role = await SysRoleModel.findOne({
      where: { id: roleId, is_deleted: 0 }
    });
    if (!role) {
      throw new Error('角色不存在');
    }

    // 使用事务确保数据一致性
    const t = await models.sequelize.transaction();
    try {
      // 删除原有菜单关联
      await SysRoleMenuModel.destroy({
        where: { role_id: roleId },
        transaction: t
      });

      // 创建新的菜单关联
      if (menuIds && menuIds.length > 0) {
        const roleMenus = menuIds.map(menuId => ({
          role_id: roleId,
          menu_id: menuId
        }));
        await SysRoleMenuModel.bulkCreate(roleMenus, { 
          fields: ['role_id', 'menu_id'],
          transaction: t
        });
      }

      await t.commit();
    } catch (error) {
      await t.rollback();
      throw error;
    }
  }

  // 获取角色菜单
  async getRoleMenuIds(roleId) {
    // 使用正确的字段名role_id而不是roleId
    const roleMenus = await SysRoleMenuModel.findAll({
      where: { roleId: roleId },
      attributes: ['menu_id']
    });
    
    // 只返回菜单ID数组，更加简洁明了
    return roleMenus.map(item => item.menu_id);
  }

  // 获取角色下拉选项
  async getRoleOptions() {
    const roles = await SysRoleModel.findAll({
      where: {
        status: 1,  // 只获取启用状态的角色
        is_deleted: 0
      },
      attributes: ['id', 'name', 'code'],
      order: [['sort', 'ASC']]
    });

    return roles.map(role => ({
      value: role.id,
      label: role.name,
      tag: role.code
    }));
  }
}

module.exports = new RoleService();